package bll

import (
	"context"
	"maya-service/store/mysql"

	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/model/mapping"
	"maya-service/store"
	"time"
)

type aiModule struct {
	iAiModule store.IAiModule
}

var AiModule = &aiModule{
	iAiModule: mysql.AiModule,
}

func init() {
	Register(AiModule)
}

func (a *aiModule) init() func() {
	return func() {}
}

// Create
func (a *aiModule) Create(ctx context.Context, in *model.AiModuleCreateRequest) error {
	var (
		err error
	)
	c := buildAiModule(in)
	_, err = a.iAiModule.Create(ctx, c)
	return err
}

// Update
func (a *aiModule) Update(ctx context.Context, in *model.AiModuleUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.Name != nil {
		dict["name"] = in.Name
	}

	if in.Images != nil {
		dict["images"] = in.Images
	}

	if in.BotId != nil {
		dict["bot_id"] = in.BotId
	}

	if in.AccessToken != nil {
		dict["access_token"] = in.AccessToken
	}

	if in.CreatedAt != nil {
		dict["created_at"] = in.CreatedAt
	}

	if in.BotId != nil {
		dict["bot_id"] = in.BotId
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	if in.Heat != nil {
		dict["heat"] = in.Heat
	}

	// do other update here
	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt
	return a.iAiModule.Update(ctx, in.Id, dict)
}

// Delete
func (a *aiModule) Delete(ctx context.Context, in *model.AiModuleDeleteRequest) error {
	return a.iAiModule.Delete(ctx, in.Id)
}

// List
func (a *aiModule) List(ctx context.Context, in *model.AiModuleListRequest) (*model.AiModuleListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.AiModule
		out   = &model.AiModuleListResponse{}
	)

	if total, list, err = a.iAiModule.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = mapping.AiModulesEntityToDto(list)

	return out, nil
}

// Find
func (a *aiModule) Find(ctx context.Context, in *model.AiModuleInfoRequest) (*model.AiModuleInfo, error) {
	var (
		err  error
		data *entity.AiModule
		out  = &model.AiModuleInfo{}
	)

	if data, err = a.iAiModule.Find(ctx, in); err != nil {
		return nil, err
	}

	out = mapping.AiModuleEntityToDto(data)
	return out, nil
}

// buildAiModule build entity
func buildAiModule(in *model.AiModuleCreateRequest) *entity.AiModule {

	ety := &entity.AiModule{}

	ety.Name = in.Name

	ety.Images = in.Images

	ety.BotId = in.BotId

	ety.AccessToken = in.AccessToken

	ety.Heat = in.Heat

	ety.CreatedAt = time.Now().Unix()

	ety.UpdatedAt = in.UpdatedAt

	return ety
}
